package com.joysuch.wwyt.api.sync.service.impl;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.joysuch.wwyt.api.sync.SyncConstants;
import com.joysuch.wwyt.api.sync.SyncJobUtil;
import com.joysuch.wwyt.api.sync.SyncResponse;
import com.joysuch.wwyt.api.sync.bean.BaseSyncContractorStaffBean;
import com.joysuch.wwyt.api.sync.service.BaseSyncContractorStaffService;
import com.joysuch.wwyt.bp.entity.contractor.BpContractor;
import com.joysuch.wwyt.bp.entity.contractor.BpContractorStaff;
import com.joysuch.wwyt.bp.repository.BpContractorDao;
import com.joysuch.wwyt.bp.repository.BpContractorStaffDao;
import com.joysuch.wwyt.core.common.ajax.ResultBean;
import com.joysuch.wwyt.core.entity.BaseConfig;
import com.joysuch.wwyt.core.entity.BaseUser;
import com.joysuch.wwyt.core.service.BaseConfigService;
import com.joysuch.wwyt.monitoringcenter.service.LocateServerService;
import com.joysuch.wwyt.util.SnowFlakeUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class BaseSyncContractorStaffServiceImpl implements BaseSyncContractorStaffService {

    @Autowired
    private BaseConfigService baseConfigService;

    @Autowired
    private BpContractorStaffDao bpContractorStaffDao;

    @Autowired
    private BpContractorDao bpContractorDao;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private LocateServerService locateServerService;


    @Override
    public ResultBean syncContractorStaff() {
        log.info("承包商人员列表同步Job 开始 ...");
        Set<String> bukrs = SyncConstants.unitCodeMap.keySet();
        List<String> msgList = new ArrayList<>();
        for(String companyCode: bukrs){
            try {
                ResultBean result = syncContractorStaffByCompany(companyCode);
                msgList.add(result.getData().toString());
            }catch(Exception e){
                log.error("承包商人员列表同步出错： companyCode={}",companyCode,e);
            }
        }
        log.info("承包商人员列表同步Job 结束 ...");
        return ResultBean.success(msgList);
    }

    @Override
    public ResultBean syncContractorStaffByCompany(String companyCode) {
        BaseConfig config = baseConfigService.findConfig(SyncConstants.TENENT_ID_DEFAULT, companyCode, SyncConstants.BASE_CONFIG_CONTRACTOR_USER_LIST_URL);
        if (config != null && StringUtils.isNotEmpty(config.getValue())) {
            HttpHeaders header = new HttpHeaders();
            header.setContentType(MediaType.APPLICATION_JSON);
            //set request body
            HttpEntity<String> requestBody = new HttpEntity<String>(companyCode, header);
            log.info("承包商人员列表同步Job：url={}, param={}", config.getValue());

            SyncResponse response = restTemplate.postForObject(config.getValue(), requestBody, SyncResponse.class);
            if (response.getMsgcode().equals("0")) {
                if (response.getData() == null) {
                    log.info("承包商人员列表同步Job： 获取数据列表为空， URL={}", config.getValue());
                    return ResultBean.success("承包商人员列表同步完成：  共同步0条记录；");
                }
                String data = JSONObject.toJSONString(response.getData());

                JSONObject content = JSONObject.parseObject(data);
                Integer count= processList(content.getString("content"), companyCode);


                return ResultBean.success("承包商人员列表同步结束： 共同步" + count.toString() + "条记录；" );
            } else {
                log.error("承包商人员列表同步Job： 接口数据获取失败： {}", response);
                return ResultBean.success("承包商人员列表同步失败：  接口数据获取失败；");
            }
        }
        return ResultBean.success("承包商人员列表同步失败：  同步接口未配置；");

    }


    // 人员信息处理
    private Integer processList (String content, String companyCode){
        if(content == null){
            return 0;
        }
        List<BaseSyncContractorStaffBean> list = JSONArray.parseArray(content, BaseSyncContractorStaffBean.class );
        log.info(".... 承包商人员同步Job： 共查询列表 list:{} ....", list.size());
        Map<String, Long> contractMap = getContractMap(companyCode);
        List<BpContractorStaff> conList = new ArrayList<>();
        int count = 0;
        List<BpContractorStaff> syncList = new ArrayList<>();
        for(BaseSyncContractorStaffBean bean: list){
            if(bean.getOrgCode() == null || !companyCode.equals(bean.getOrgCode())){
                continue;
            }

            BpContractorStaff staff = bpContractorStaffDao.findByCodeAndCompanyCode(bean.getCode(),bean.getOrgCode());
            if(staff == null){
                staff = new BpContractorStaff();
                staff.setCode(bean.getCode());
                staff.setDeleteFlag("0");
                staff.setIdentity(1);
                staff.setName(bean.getRealName());
                staff.setRefUrl(bean.getRefUrl());
                staff.setIdCardNo(bean.getIdCardNumber());
                staff.setFacePic(bean.getFacePic());
                if(bean.getCompanyCode() != null){
                    staff.setContractorId(contractMap.get(bean.getCompanyCode()));
                }
                staff.setCardNumber(bean.getCardNumber());
                staff.setSn(bean.getSn());
                staff.setFacePic(bean.getFacePic());
                //是否合格
                if(StringUtils.isEmpty(bean.getState())){
                    staff.setState(0);
                }else{
                    staff.setState("Y".equalsIgnoreCase(bean.getState()) ? 1 : 0);
                }
                staff.setTenentId(SyncConstants.TENENT_ID_DEFAULT);
                staff.setOrgCode(bean.getOrgCode());

                staff.setUniqueId(SnowFlakeUtil.getContractorStaffId());
                staff.setCapId(3L);
                staff.setLocateSync(false);
                count ++;
                conList.add(staff);
            }else{
                if(SyncJobUtil.checkIfDifferent(staff.getName(),bean.getRealName())
                        ||SyncJobUtil.checkIfDifferent(staff.getRefUrl(),bean.getRefUrl())
                || SyncJobUtil.checkIfDifferent(staff.getIdCardNo(),bean.getIdCardNumber())
                        ||SyncJobUtil.checkIfDifferent(staff.getSn(),bean.getSn())
                || SyncJobUtil.checkIfDifferent(staff.getFacePic(),bean.getFacePic())
                        || SyncJobUtil.checkIfDifferent(staff.getContractorId(),contractMap.get(bean.getCompanyCode()))
                || SyncJobUtil.checkIfDifferent(staff.getCardNumber(),bean.getCardNumber())
                        ||SyncJobUtil.checkIfDifferent(staff.getState(),"Y".equalsIgnoreCase(bean.getState()) ? 1 : 0) ){
                    staff.setName(bean.getRealName());
                    staff.setRefUrl(bean.getRefUrl());
                    staff.setIdCardNo(bean.getIdCardNumber());

                    staff.setFacePic(bean.getFacePic());
                    if(bean.getCompanyCode() != null){
                        staff.setContractorId(contractMap.get(bean.getCompanyCode()));
                    }
                    staff.setCardNumber(bean.getCardNumber());
                    staff.setSn(bean.getSn());
                    //是否合格
                    if(StringUtils.isEmpty(bean.getState())){
                        staff.setState(0);
                    }else{
                        staff.setState("Y".equalsIgnoreCase(bean.getState()) ? 1 : 0);
                    }
                    if(StringUtils.isEmpty(staff.getUniqueId())){
                        staff.setUniqueId(SnowFlakeUtil.getContractorStaffId());
                    }
                    if(staff.getCapId() == null){
                        staff.setCapId(3L);
                    }

                    count ++;
                    conList.add(staff);
                }
            }
            //批量更新， 每100 个更新一批
            if(conList.size() >=100){
                bpContractorStaffDao.saveAll(conList);
                log.info(".... 承包商人员同步Job： 已同步承包商人员列表 list:{} ....", conList.size());
                //调用接口，同步到人员在岗在位系统
                syncList = conList.stream().filter(it-> StringUtils.isNotEmpty(it.getSn())).collect(Collectors.toList());
                if(!syncList.isEmpty()){
                    locateServerService.syncLocateUsers(syncList,1);
                    syncList = Collections.EMPTY_LIST;
                }

                conList = new ArrayList<>();
            }
        }
        if(conList.size() >0){
            bpContractorStaffDao.saveAll(conList);
            syncList = conList.stream().filter(it-> StringUtils.isNotEmpty(it.getSn())).collect(Collectors.toList());
            if(!syncList.isEmpty()){
                locateServerService.syncLocateUsers(syncList,1);
            }
            log.info(".... 承包商人员同步Job： 已同步承包商人员列表 list:{} ....", conList.size());
        }

        return count;
    }


    private Map<String,Long> getContractMap(String orgCode){
        Map<String, Long> map = new HashMap<>();
        List<BpContractor> list = bpContractorDao.findAllContractorByCompanyCode(orgCode);

        if(list != null){
            for(BpContractor c: list){
                map.put(c.getCode(), c.getId());
            }
        }

        return map;
    }

}
